package com.bjsxt.web.listener;

import com.bjsxt.commons.Constants;
import com.bjsxt.pojo.Users;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//解决HttpSession超时销毁时的异常问题
@WebListener
public class HttpSessionLifeccycleListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {

    }

    //session 销毁前会自动启的方法
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        //获取ServletContext对象 然后将对应的HttpSession删除
        HttpSession session = se.getSession();
        //获得ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //用session取得对应的User
        Users users = (Users) session.getAttribute(Constants.USER_SESSION_KEY);
        // id在session中是唯一的  根据userid 删除对应的session
        servletContext.removeAttribute(users.getUserid()+"");

    }
}
